package com.sofwin.intercept;

import com.sofwin.Constants;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.MonitorService;
import com.sofwin.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Component
public class MonitorIntercept implements HandlerInterceptor {
    private long beginDate;

    @Autowired
    private MonitorService monitorService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        beginDate = System.currentTimeMillis();
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       long endDate = System.currentTimeMillis();
       long request_date = endDate-beginDate;//执行时间
        //获取当前用户
        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute(Constants.CURR_USER);
        String ip = request.getRemoteAddr();//IP地址
        String url = request.getRequestURI();//获取Url
        String currDate = DateUtil.getDateStr(new Date(),"yyyy-MM-dd HH:mm:ss");//当前时间

       monitorService.saveMonitor(user.getId(),url,currDate,request_date,ip);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
